-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.py
More file actions
24 lines (23 loc) · 737 Bytes
/
Solution.py
File metadata and controls
24 lines (23 loc) · 737 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def evaluate_postfix(expression):
stack = []
for ch in expression:
if ch.isdigit():
stack.append(int(ch))
else:
val2 = stack.pop()
val1 = stack.pop()
if ch == '+':
stack.append(val1 + val2)
elif ch == '-':
stack.append(val1 - val2)
elif ch == '*':
stack.append(val1 * val2)
elif ch == '/':
stack.append(val1 // val2)
elif ch == '^':
stack.append(val1 ** val2)
return stack.pop()
if __name__ == "__main__":
expression = input("Enter postfix expression: ")
result = evaluate_postfix(expression)
print(f"Result: {result}")